use crate::{xcontainer::DynContainerReadItem, chunk_meta::ChunkKind, constants::DefaultFingerprintType};

const PREFIX_LEN:usize = std::mem::size_of::<DefaultFingerprintType>();

pub struct XreChunk {
    kind:ChunkKind,
    data:Box<[u8]>,
}

impl XreChunk {
	pub fn unique_unwrap(&self) -> Option<&[u8]> {
		self.kind.is_unique().then_some(&self.data)
	}

    pub fn base_fp(&self) -> Option<&DefaultFingerprintType> {
        //self.kind.is_delta().then_some((&self.data[0..PREFIX_LEN]).try_into().unwrap())
        todo!()
    }

	pub fn origin_max_len(&self) -> usize {
		0xffffffff
	}

    pub fn decode(&self,base_chunk:&XreChunk) -> Option<Vec<u8>>{
        let base = base_chunk.unique_unwrap()?;
        let delta = self.kind.is_delta().then_some(&self.data[PREFIX_LEN..])?;
        xdelta3::decode(delta, base, self.origin_max_len())
    }
}


impl DynContainerReadItem for XreChunk {
	type Meta = (ChunkKind,DefaultFingerprintType);
    fn from_meta(meta:&(crate::xcontainer::OffsetMeta,Self::Meta)) -> Self {
        unsafe {
            Self {
                kind:meta.1.0,
                data:Box::new_uninit_slice(meta.0.try_into().unwrap()).assume_init(),
            }
        }
    }

    fn as_data_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }

}